﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class File2Code : UserControl
    {


        //实例化文件对话框的类对象
        OpenFileDialog ofg = new OpenFileDialog();


        SaveFileDialog sfg = new SaveFileDialog();

        //存放源文件路径，一个存放目的文件路径
        string filepath;
        string filepath1;




        public File2Code()
        {
            InitializeComponent();

            comboBox1.SelectedIndex = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //调用对象的函数
            if (ofg.ShowDialog() == DialogResult.OK)
            {
                //获取文件的路径
                filepath = ofg.FileName;
                this.textBox1.Text = filepath;

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == -1)
                return;

            //调用对象的函数
            if (sfg.ShowDialog() != DialogResult.OK)
                return;

            try
            {
                var buffer = File.ReadAllBytes(filepath);

                StringBuilder sb = new StringBuilder();
                sb.Append(@"//");
                sb.Append(ofg.FileName);
                sb.Append("\n");


                switch (comboBox1.SelectedIndex)
                {
                    case 0:
                        sb.Append("unsigned char buffer[0x"+buffer.Length.ToString("X")+ "] = {\n");
                        break;
                    case 1:
                        sb.Append("byte[] buffer = new byte[] {\n");
                        break;

                }


                int lines = buffer.Length / 16;
                int others = buffer.Length % 16;

                for (int y = 0; y <= lines; y++)
                {
                    //行数遍历  
                    sb.Append("\t");
                    for (int x = 0; y == lines ? x < others : x < 16; x++)
                    {
                        sb.Append("0x");
                        sb.Append(buffer[y * 16 + x].ToString("X2"));
                        sb.Append(",");
                    }
                    sb.Append("\n");

                }
                sb.Append("\n};");


                File.WriteAllText(sfg.FileName, sb.ToString());

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }

        }
    }
}
